<template>
  <div>
    <BasicModal v-bind="$attrs" :helpMessage="'提示1'" @ok="okClick" @register="registerModal">
      <BasicForm @register="registerForm" />
    </BasicModal>
    <SetPassword @register="setUserRegister" @close-model-flag="closeModelFlag" />
  </div>
</template>

<script setup lang="ts">
  import SetPassword from './SetPassword.vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { addTheUser, getTheUserLink } from '/@/api/thingsborad/customers/customers';
  import { useUserStore } from '/@/store/modules/user';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { ref } from 'vue';
  import { useModal } from '/@/components/Modal';

  // 组件通信
  const emits = defineEmits(['closeModelFlag']);
  //用户登录数据
  const userStore = useUserStore();
  // 获取用户登录信息
  const userInfo = ref<any>(userStore.userInfo);
  // 提示弹窗

  //登录用户id
  let customerId = ref<any>();
  //打开弹窗的方式
  let isEdit = ref<boolean>(false);
  //编辑详情
  let editInfo = ref<any>();
  //表格字段
  const schemas: FormSchema[] = [
    {
      field: 'EMail',
      component: 'Input',
      label: '电子邮件',
      rules: [
        {
          required: true,
          // @ts-ignore
          validator: async (rule, value) => {
            const emailRegex =
              /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if (emailRegex.test(value) === false) {
              return Promise.reject('电子邮件格式不正确');
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
      componentProps: {
        placeholder: '请输入电子邮件',
      },
    },
    {
      field: 'firstName',
      component: 'Input',
      label: '名字',

      componentProps: {
        placeholder: '请输入名字',
      },
    },
    {
      field: 'phoneNumber',
      component: 'Input',
      label: '手机号码',
      rules: [
        {
          required: true,
          // @ts-ignore
          validator: async (rule, value) => {
            const regex = /^1[3-9]\d{9}$/;
            if (regex.test(value) === false) {
              return Promise.reject('手机号码格式不正确');
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
      componentProps: {
        placeholder: '例如：13123456789',
      },
    },

    {
      field: 'activationMethod',
      component: 'Select',
      label: '激活方式',
      defaultValue: 'CUSTOMER_USER',
      componentProps: {
        options: [
          {
            label: '显示激活链接',
            value: 'CUSTOMER_USER',
          },
        ],
      },
    },
    {
      field: 'describe',
      component: 'InputTextArea',
      label: '说明',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请输入说明',
      },
    },
  ];

  // 初始化弹窗
  const [
    setUserRegister,
    { openModal: setopenModal, setModalProps: setSetModalProps, closeModal: setCloseModal },
  ] = useModal();

  // 打开表格时数据初始化
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    
    if (data.key !== undefined && data.key === '编辑') {
      isEdit.value = true;
      editInfo.value = data.record.info;
      setFieldsValue({
        EMail: data.record.email,
        firstName: data.record.firstName,
        phoneNumber:
          data.record.info.phone === null ? '' : data.record.info.phone.replace(/^\+86/, ''),
        describe: data.record.info.additionalInfo.description,
      });
    }
    customerId.value = data.id;
    setModalProps({
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
  });
  // 表格初始化
  const [registerForm, { setFieldsValue, validate, resetFields }] = useForm({
    layout: 'vertical',
    schemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  // 保存
  const okClick = async () => {
    const validateFlag = await validate();

    let params: any;
    if (isEdit.value) {
      params = {
        params: {
          sendActivationMail: false,
        },
        data: {
          id: editInfo.value.id,
          createdTime: editInfo.value.createdTime,
          additionalInfo: {
            description: validateFlag.describe,
            defaultDashboardId: null,
            defaultDashboardFullscreen: false,
            homeDashboardId: null,
            homeDashboardHideToolbar: true,
          },
          tenantId: editInfo.value.tenantId,
          customerId: editInfo.value.customerId,
          email: validateFlag.EMail,
          authority: 'CUSTOMER_USER',
          firstName: validateFlag.firstName,
          lastName: '',
          phone: '+86' + validateFlag.phoneNumber,
          name: validateFlag.EMail,
        },
      };
    } else {
      params = {
        params: {
          sendActivationMail: false,
        },
        data: {
          email: validateFlag.EMail,
          firstName: validateFlag.firstName,
          lastName: '',
          phone: '+86' + validateFlag.phoneNumber,
          additionalInfo: {
            description: validateFlag.describe,
            defaultDashboardId: null,
            defaultDashboardFullscreen: false,
            homeDashboardId: null,
            homeDashboardHideToolbar: true,
          },
          authority: 'CUSTOMER_USER',
          tenantId: userInfo.value.tenantId,
          customerId: customerId.value,
        },
      };
    }
    const userData = await addTheUser(params);
    resetFields();
    closeModal();
    const link = await getTheUserLink(userData.id.id);

    setSetModalProps({
      title: '设置密码',
    });

    setopenModal(true, link);
  };

  // 关闭弹窗
  function closeModelFlag() {
    emits('closeModelFlag', 'close');
    setCloseModal();
  }
</script>
